{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "9905f163-759f-474b-8f7a-7d14da0df44d",
   "metadata": {},
   "source": [
    "### BUSINESS CHALLENGE: Using Multi-shot Prompting\n",
    "#### Day 5\n",
    "\n",
    "Create a product that builds a Brochure for a company to be used for prospective clients, investors and potential recruits.\n",
    "\n",
    "We will be provided a company name and their primary website."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a0895f24-65ff-4624-8ae0-15d2d400d8f0",
   "metadata": {},
   "outputs": [],
   "source": [
    "# imports\n",
    "# If these fail, please check you're running from an 'activated' environment with (llms) in the command prompt\n",
    "\n",
    "import os\n",
    "import requests\n",
    "import json\n",
    "from typing import List\n",
    "from dotenv import load_dotenv\n",
    "from bs4 import BeautifulSoup\n",
    "from IPython.display import Markdown, display, update_display\n",
    "from openai import OpenAI"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7794aa70-5962-4669-b86f-b53639f4f9ea",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Initialize and constants\n",
    "\n",
    "load_dotenv(override=True)\n",
    "api_key = os.getenv('OPENAI_API_KEY')\n",
    "\n",
    "if api_key and api_key.startswith('sk-proj-') and len(api_key)>10:\n",
    "    print(\"API key looks good so far\")\n",
    "else:\n",
    "    print(\"There might be a problem with your API key? Please visit the troubleshooting notebook!\")\n",
    "    \n",
    "MODEL = 'gpt-4o-mini'\n",
    "openai = OpenAI()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "63bf8631-2746-4255-bec1-522855d3e812",
   "metadata": {},
   "outputs": [],
   "source": [
    "# A class to represent a Webpage\n",
    "\n",
    "# Some websites need you to use proper headers when fetching them:\n",
    "headers = {\n",
    " \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36\"\n",
    "}\n",
    "\n",
    "class Website:\n",
    "    \"\"\"\n",
    "    A utility class to represent a Website that we have scraped, now with links\n",
    "    \"\"\"\n",
    "\n",
    "    def __init__(self, url):\n",
    "        self.url = url\n",
    "        response = requests.get(url, headers=headers)\n",
    "        self.body = response.content\n",
    "        soup = BeautifulSoup(self.body, 'html.parser')\n",
    "        self.title = soup.title.string if soup.title else \"No title found\"\n",
    "        if soup.body:\n",
    "            for irrelevant in soup.body([\"script\", \"style\", \"img\", \"input\"]):\n",
    "                irrelevant.decompose()\n",
    "            self.text = soup.body.get_text(separator=\"\\n\", strip=True)\n",
    "        else:\n",
    "            self.text = \"\"\n",
    "        links = [link.get('href') for link in soup.find_all('a')]\n",
    "        self.links = [link for link in links if link]\n",
    "\n",
    "    def get_contents(self):\n",
    "        return f\"Webpage Title:\\n{self.title}\\nWebpage Contents:\\n{self.text}\\n\\n\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1e7bb527-e769-4245-bb91-ae65e64593ff",
   "metadata": {},
   "source": [
    "## First step: Have GPT-4o-mini figure out which links are relevant\n",
    "\n",
    "### Use a call to gpt-4o-mini to read the links on a webpage, and respond in structured JSON. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1ce303ae-b967-4261-aadc-02dafa54db4a",
   "metadata": {},
   "outputs": [],
   "source": [
    "link_system_prompt = \"You are provided with a list of links found on a webpage. \\\n",
    "You are able to decide which of the links would be most relevant to include in a brochure about the company, \\\n",
    "such as links to an About page, or a Company page, or Careers/Jobs pages.\\n\"\n",
    "link_system_prompt += \"You should respond in JSON as in this example:\"\n",
    "link_system_prompt += \"\"\"\n",
    "{\n",
    "    \"links\": [\n",
    "        {\"type\": \"about page\", \"url\": \"https://full.url/goes/here/about\"},\n",
    "        {\"type\": \"careers page\", \"url\": \"https://another.full.url/careers\"}\n",
    "    ]\n",
    "}\n",
    "\"\"\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d24a4c0c-a1d1-4897-b2a7-4128d25c2e08",
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_links_user_prompt(website):\n",
    "    user_prompt = f\"Here is the list of links on the website of {website.url} - \"\n",
    "    user_prompt += \"please decide which of these are relevant web links for a brochure about the company, respond with the full https URL in JSON format. \\\n",
    "Do not include Terms of Service, Privacy, email links.\\n\"\n",
    "    user_prompt += \"Links (some might be relative links):\\n\"\n",
    "    user_prompt += \"\\n\".join(website.links)\n",
    "    return user_prompt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8103fc11-5bc0-41c4-8c97-502c9e96429c",
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_links(url): # 1st inference\n",
    "    website = Website(url)\n",
    "    response = openai.chat.completions.create(\n",
    "        model=MODEL,\n",
    "        messages=[\n",
    "            {\"role\": \"system\", \"content\": link_system_prompt},\n",
    "            {\"role\": \"user\", \"content\": get_links_user_prompt(website)}\n",
    "      ],\n",
    "        response_format={\"type\": \"json_object\"}\n",
    "    )\n",
    "    result = response.choices[0].message.content\n",
    "    return json.loads(result)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dc84a695-515d-4292-9a95-818f4fe3d20e",
   "metadata": {},
   "outputs": [],
   "source": [
    "huggingface = Website(\"https://huggingface.co\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "91896908-1632-41fc-9b8b-39a7638d8dd1",
   "metadata": {},
   "source": [
    "## Second step: make the brochure!\n",
    "\n",
    "Assemble all the details into another prompt to GPT4-o"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ab7c54e3-e654-4b1f-8671-09194b628aa0",
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_all_details(url): # 1st inference wrapper\n",
    "    result = \"Landing page:\\n\"\n",
    "    result += Website(url).get_contents()\n",
    "    links = get_links(url) # inference\n",
    "    # print(\"Found links:\", links)\n",
    "    for link in links[\"links\"]:\n",
    "        result += f\"\\n\\n{link['type']}\\n\"\n",
    "        result += Website(link[\"url\"]).get_contents()\n",
    "    return result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ea9f54d1-a248-4c56-a1de-6633193de5bf",
   "metadata": {},
   "outputs": [],
   "source": [
    "system_prompt = \"You are an assistant that analyzes the contents of several relevant pages from a company website \\\n",
    "and creates a short humorous, entertaining, jokey brochure about the company for prospective customers, investors and recruits. Respond in markdown.\\\n",
    "Include details of company culture, customers and careers/jobs if you have the information.\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "13412c85-badd-4d79-a5ac-8283e4bb832f",
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_brochure_user_prompt(company_name, url):\n",
    "    user_prompt = f\"You are looking at a company called: {company_name}\\n\"\n",
    "    user_prompt += f\"Here are the contents of its landing page and other relevant pages; use this information to build a short brochure of the company in markdown.\\n\"\n",
    "    user_prompt += get_all_details(url) # inference wrapper\n",
    "    user_prompt = user_prompt[:5_000] # Truncate if more than 5,000 characters\n",
    "    return user_prompt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "addc0047-ea73-4748-abc3-747ff343c134",
   "metadata": {},
   "outputs": [],
   "source": [
    "def create_brochure(company_name, url): # 2nd inference\n",
    "    response = openai.chat.completions.create(\n",
    "        model=MODEL,\n",
    "        messages=[\n",
    "            {\"role\": \"system\", \"content\": system_prompt},\n",
    "            {\"role\": \"user\", \"content\": get_brochure_user_prompt(company_name, url)}\n",
    "          ],\n",
    "    )\n",
    "    result = response.choices[0].message.content\n",
    "    return result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "82a3b61a-da26-4265-840a-0a93f81cd048",
   "metadata": {},
   "outputs": [],
   "source": [
    "brochure_english = create_brochure(\"HuggingFace\", \"https://huggingface.co\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5d165e3f-8fe2-4712-b098-d34d9fabe583",
   "metadata": {},
   "outputs": [],
   "source": [
    "display(Markdown(brochure_english))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "107a2100-3f7d-4f16-8ba7-b5da602393c6",
   "metadata": {},
   "outputs": [],
   "source": [
    "def stream_brochure(company_name, url):\n",
    "    stream = openai.chat.completions.create(\n",
    "        model=MODEL,\n",
    "        messages=[\n",
    "            {\"role\": \"system\", \"content\": system_prompt},\n",
    "            {\"role\": \"user\", \"content\": get_brochure_user_prompt(company_name, url)}\n",
    "          ],\n",
    "        stream=True\n",
    "    )\n",
    "    \n",
    "    response = \"\"\n",
    "    display_handle = display(Markdown(\"\"), display_id=True)\n",
    "    for chunk in stream:\n",
    "        response += chunk.choices[0].delta.content or ''\n",
    "        response = response.replace(\"```\",\"\").replace(\"markdown\", \"\")\n",
    "        update_display(Markdown(response), display_id=display_handle.display_id)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "26cbe9b5-3603-49a1-a676-75c7ddaacdb8",
   "metadata": {},
   "outputs": [],
   "source": [
    "stream_brochure(\"HuggingFace\", \"https://huggingface.co\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c10d8189-7f79-4991-abc4-0764369b7d64",
   "metadata": {},
   "source": [
    "### Third step: Translate the entire brochure to Spanish"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "666817eb-1e8b-4fee-bbab-c0dbfe2ea7c0",
   "metadata": {},
   "outputs": [],
   "source": [
    "system_prompt = \"You are an assistant that analyzes the contents of a brochure \\\n",
    "and translates to Spanish. Respond in markdown.\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c48adb12-bc3c-48f9-ab38-b7ca895195f6",
   "metadata": {},
   "outputs": [],
   "source": [
    "def translate_user_prompt(company_name, url):\n",
    "    user_prompt = f\"Please translate the following brochure content to Spanish\\n\"\n",
    "    user_prompt += create_brochure(company_name, url) # inference wrapper\n",
    "    # user_prompt = user_prompt[:5_000] # Truncate if more than 5,000 characters\n",
    "    return user_prompt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b92b61ac-3be3-4e84-9000-ec8233697b81",
   "metadata": {},
   "outputs": [],
   "source": [
    "translate_user_prompt(\"HuggingFace\", \"https://huggingface.co\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6bfd04f4-4381-4730-ac5d-c9fa02f906df",
   "metadata": {},
   "outputs": [],
   "source": [
    "def translate_brochure(): # 3rd inference\n",
    "    stream = openai.chat.completions.create(\n",
    "        model=MODEL,\n",
    "        messages=[\n",
    "            {\"role\": \"system\", \"content\": system_prompt},\n",
    "            {\"role\": \"user\", \"content\": translate_user_prompt(\"HuggingFace\", \"https://huggingface.co\")}\n",
    "          ],\n",
    "        stream=True\n",
    "    )\n",
    "    \n",
    "    response = \"\"\n",
    "    display_handle = display(Markdown(\"\"), display_id=True)\n",
    "    for chunk in stream:\n",
    "        response += chunk.choices[0].delta.content or ''\n",
    "        response = response.replace(\"```\",\"\").replace(\"markdown\", \"\")\n",
    "        update_display(Markdown(response), display_id=display_handle.display_id)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bb78ed28-9ecd-4c08-ae96-d7473cbc97dd",
   "metadata": {},
   "outputs": [],
   "source": [
    "translate_brochure()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
